<template>
  <div class="app-container">
    <el-divider content-position="left">考试信息</el-divider>
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-row>
        <el-col :span="8">
        <el-form-item label="考试名称" prop="examName">
          <el-input v-model="form.examName" style="width: 70%" placeholder="请输入考试名称" />
        </el-form-item>
        </el-col>
        <el-col :span="8">
        <el-form-item label="考试课程" prop="courseTypeOptions">
          <el-select
            v-model="form.courseName"
            clearable
            filterable
            :disabled="disabled"
            style="width: 70%"
            @change="selectCourse($event)"
          >
            <el-option
              v-for="(item, index) of courseTypeOptions"
              :label="item.courseName"
              placeholder="选择考试课程"
              :value="{value:item.id,label:item.courseName}"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
         </el-col>
         <el-col :span="8">
        <el-form-item label="考试班级" prop="classId">
          <el-select
            v-model="form.className"
            clearable
            filterable
            :disabled="disabled"
            style="width: 70%"
            @change="selectClass($event)"
          >
          <el-option
              v-for="(item, index) of classOptions"
              :key="index"
              :value="{value:item.id,label:item.className}"
              :label="item.className"
            >
          </el-option>
          </el-select>
        </el-form-item>
        </el-col>
      </el-row>
        <!-- <el-form-item label="考试班级" prop="classOptions" v-if="isUpdate">
          <el-select
            v-model="form.className"
            clearable
            filterable
            style="width: 100%"
            @change="selectClass($event)"
          >
            <el-option
              v-for="(item, index) of classOptions"
              :label="item.className"
              placeholder="选择考试班级"
              :value="{value:item.id,label:item.className}"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-row>
          <el-col :span="8">
        <el-form-item label="考试教室" prop="classRoomId">
          <el-input v-model="form.examRoom" style="width: 70%" placeholder="请输入考试教室" />
        </el-form-item>
          </el-col>
          <el-col :span="8">
        <el-form-item label="监考老师" prop="invigilationTeacher">
          <el-select
            v-model="form.invigilationTeacher"
            filterable
            placeholder="请选择"
            style="width: 70%"
          >
            <el-option
              v-for="item1 in userOptions"
              :key="item1.id"
              :label="item1.username"
              :value="item1.username"
            />
          </el-select>
        </el-form-item>
          </el-col>
          </el-row>
          <el-row>
        <el-col :span="8">
        <el-form-item label="考试开始时间" prop="examBeginTime">
          <el-date-picker
            style="width: 70%"
            v-model="form.examBeginTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择开始日期时间"
          >
          </el-date-picker>
        </el-form-item>
        </el-col>
        <el-col :span="8">
        <el-form-item label="考试结束时间" prop="examEndTime">
          <el-date-picker
            style="width: 70%"
            v-model="form.examEndTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择开始日期时间"
          >
          </el-date-picker>
        </el-form-item>
          </el-col>
        </el-row> 

      <el-divider content-position="left">考试名单</el-divider>
      <el-row>
      <el-table :data="form.examStudents" prop="examStudents">
            <el-table-column label="序号" align="center" type="index" />
            <el-table-column
              label="学生姓名"
              align="center"
              prop="studentName"
            />
            <el-table-column label="学号" align="center" prop="studentNo" />
            <el-table-column label="考试分数" align="center" prop="score">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.score"
                  placeholder="分数"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="是否通过" align="center" prop="isPass">
              <template slot-scope="scope">
                <el-radio v-model="scope.row.isPass" label="0">不通过</el-radio>
                <el-radio v-model="scope.row.isPass" label="1">通过</el-radio>
              </template>
            </el-table-column>
      </el-table>
  </el-row>
      </el-form>
      <div style="text-align: center;margin-top: 10px;">
            <el-button type="primary" @click="onSubmit" :loading="submitLoading">提 交</el-button>
            <el-button @click="cancel">返 回</el-button>
        </div>
  </div>
</template>
  
<script>
import {
  queryExam,
  queryClassStudents,
  editExamResult,
  pageList,
  queryExamResult,
  queryMakeUpExamResult,
  findExamDetail,
  findExamStudentsByResit
} from "@/api/exam/examResultEnter";
import { findAllCourse } from "@/api/basedata/bcourse";
import { listAllBClass } from "@/api/basedata/bclass";
import { getClassTeacherList } from "@/api/system/user";


export default {
  name: "examEnter",
  data() {
    return {
      // 遮罩层
      loading: true,
      submitLoading: false,
      // 选中数组
      rowList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 字典表格数据
      examResultList: [],
      // 是否禁用
      disabled:false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        className: undefined,
        examName: undefined,
        examRecord: undefined
      },
      // 表单参数
      form: {
        examId: undefined,
        examName:undefined,
        examStudents: [],
      },
      // 表单校验
      rules: {
        examName: [
          { required: true, message: "请选择考试名称", trigger: "blur" },
        ],
        courseTypeOptions: [
          { required: true, message: "请选择课程", trigger: "blur"},
        ],
        classId: [
          { required: true, message: "请选择班级", trigger: "blur"}
        ],
      },
      examOptions: [],
      examItem: {},
      examResult: {},
      classNameItem: [],
      courseTypeOptions: [],
      classOptions: [],
      userOptions: [],
      examId: null,
      examRecord: null,
      studentExamItem: [],
      classList: [],
    };
  },
  created() {
    this.getAllCourse();
    this.getClassList();
    this.getClassTeacherList();

    this.examId = this.$route.query.id;
    this.examRecord = this.$route.query.examRecord;
    // if(this.examRecord) {
    //   // 查找补考的名单
    //   findExamStudentsByResit(this.examId).then(response => {
    //     this.studentExamItem = response.data
    //   })
    // }
    if(this.examId) {
      this.disabled = true;
      findExamDetail({examId: this.examId, examRecord: this.examRecord}).then(response => {
        this.form = response.data;
        this.form.examRecord = this.examRecord;
      })
    }
    console.log(this.form);
 
  },

  methods: {
    //计算百分比
    getPercent(num, total) {
      num = parseFloat(num);
      total = parseFloat(total);
      if (isNaN(num) || isNaN(total)) {
        return 0;
      }
      return total <= 0 ? "0%" : Math.round((num / total) * 10000) / 100.0;
    },
    getAllCourse() {
      findAllCourse().then((response) => {
        this.courseTypeOptions = response.data;
      });
    },
    //查询班级
    getClassList() {
      listAllBClass().then((resp) => {
        this.classOptions = resp.data;
      });
    },
       //查询监考老师
    getClassTeacherList() {
      getClassTeacherList().then((response) => {
        this.userOptions = response.data;
      });
    },
    //查询考试数据
    getExamList(val) {
      queryExam({ pageSize: 1000, pageNum: 0, examName: val }).then((resp) => {
        this.examOptions = resp.data;
      });
    },

    //通过班级id查找班级学生
    getClassStudent(classIdParam) {
      this.form.examStudents = [];
      queryClassStudents({ classId: classIdParam }).then((resp) => {
        for (let i = 0; i < resp.data.length; i++) {
          this.form.examStudents.push({
            score: "0",
            isPass: "0",
            studentNo: resp.data[i].studentNo,
            classId: resp.data[i].classId,
            studentName: resp.data[i].studentName,
          });
        }
      });
    },

    //查询考试
    selectExam(value) {
      this.form.classId = null;
      // 点击考试的时候 放置对应的班级
      this.examItem = this.examOptions.find(function (item) {
        return item.examName == value;
      });
      this.examItem.className = undefined;
      this.classList = this.examItem.classList;
    },
    selectCourse(selVal) {
            let { value, label } = selVal;
            this.form.courseId = value;
            this.form.courseName = label;
    },
    selectClass(selVal) {
      let { value, label } = selVal;
      console.log(selVal);
      this.form.classId = value;
      this.form.className = label;
      this.getClassStudent(value);
    },

    /** 查询数据列表 */
    getList() {
      this.loading = true;
      pageList(this.queryParams).then((response) => {
        this.examResultList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },

    cancel() {
      const _this = this;

            this.$confirm('确定离开此页面吗', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
               
                    _this.$router.push("/academic/examCfg")
                  }).catch(function() {
                    if(!this.examId) {
                      this.form={}
                    }
                  });
        },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.disabled = false
      this.open = true;
      this.title = "录入考试成绩";
      this.examItem = {};
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.rowList = selection;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row);
      this.reset();
      this.title = "修改考试成绩"
      this.disabled = true
      this.open = true;
      this.examItem = this.examOptions.find(function (item) {
        return item.examName == row.examName;
      });
      this.classList = this.examItem.classList;      
      const classInfo = this.classList.find(function (item) {
        return item.classId == row.classId;
      });
      this.form.examId = row.id;
      this.form.examName = row.examName;
      this.form.classId = row.classId;
      this.form.className = row.className;
      this.form.examRecord = row.examRecord;
      this.examItem.className = row.className;
      this.examItem.userName = classInfo.classTeacher;
      this.form.examStudents = [];
      queryExamResult(row).then((resp) => {
        const list = resp.data;
        console.log(list);
        this.form.id = list[0].id;
        if (list.length > 0) {
          for (let i = 0; i < list.length; i++) {
            this.form.examStudents.push({
              isPass: list[i].isPass,
              studentNo: list[i].studentNo,
              studentName: list[i].studentName,
            });
          }
        }
      });
    },
    // 录入补考成绩
    handleEnterMakeUpExamScores(row) {
      this.reset();
      this.title = "录入补考成绩"
      this.disabled = true
      this.open = true;
      this.examItem = this.examOptions.find(function (item) {
        return item.examName == row.examName;
      });
      this.classList = this.examItem.classList;      
      const classInfo = this.classList.find(function (item) {
        return item.classId == row.classId;
      });
      this.form.examId = row.id;
      this.form.examName = row.examName;
      this.form.classId = row.classId;
      this.form.className = row.className;
      this.examItem.className = row.className;
      this.examItem.userName = classInfo.classTeacher;
      this.form.examStudents = [];
      queryMakeUpExamResult(row).then((resp) => {
        const list = resp.data;
        console.log(list);
        this.form.id = list[0].id;
        if (list.length > 0) {
          for (let i = 0; i < list.length; i++) {
            this.form.examStudents.push({
              isPass: list[i].isPass,
              studentNo: list[i].studentNo,
              studentName: list[i].studentName,
            });
          }
        }
      });
    },
    onSubmit() {
        const _this = this
        this.submitLoading = true;
        this.form.examRecord = this.examRecord;
        editExamResult(this.form).then((resp) => {
          console.log(resp)
          this.submitLoading = false
          var tipStr = "";
          if(this.examId) {
             tipStr = "修改成功是否留在当前页面?"
          } else {
             tipStr = "新增成功是否留在当前页面?"
          }
          this.$confirm(tipStr, "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "返回",
                    type: "warning"
                  }).then(() => {
                    if(!this.examId) {
                      this.form={}
                    }
                    
                  }).catch(function() {
                    _this.$router.go(-1)
                  });
          });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          editExamResult(this.form).then((resp) => {
            this.msgSuccess("提交成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
  },
};
</script>